<?php
/*
Copyright (C) 2014 by Joey Sabey (GameFreak7744@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
require_once('Hook.php');

class Template {
	//Version string...
	const VERSION = 'trunk';

    const TEMPLATE_DIR = 'templates/';
    const CONTENT_DIR  = 'content/';
    const INSERT_STRICT = FALSE;

    //Flags
    const FROM_FILE    = 0;
    const FROM_STRING  = 1;

    protected $template;
    protected $hooks = [];
    protected $inserts = null;
    protected $insertRegex;

    function __construct($file, $mode = self::FROM_FILE) {
        switch($mode) {
            case self::FROM_FILE:
                $this->template = self::readTemplate($file);
                break;
            case self::FROM_STRING:
                $this->template = $file;
                break;
        }
        //Pull a tree of Hook objects from the template file
        $this->hooks = self::extractHooks($this->template);
        //Populate $inserts array
        foreach($this->getInsertStrings() as $insert) {
            $this->inserts[$insert] = [];
        }
        $this->insertRegex = self::generateInsertRegex($this->hooks);
    }

    public function __toString() {
        return $this->render();
    }

    public function render() {
        $output = $this->template;
        foreach($this->hooks as $hook) {
            $str = '';
            if($hook->isBasic()) {
                foreach($this->inserts[$hook->getID()] as $insert) {
                    $str .= $insert;
                }
                $output = str_replace($hook->getHookString(), $str, $output);
            }
            else {
                $y = 0;
                foreach($hook->getInsertStrings() as $insertStr) {
                    $y = max($y, count($this->inserts[$insertStr]));
                }
                for($x = 0; $x < $y; $x++) {
                    $template = new Template($hook->getTemplate());
                    foreach($hook->getInsertStrings() as $insertStr) {
                        $template->insert(explode(Hook::TAG_SEPARATOR, $insertStr, 2)[1], $this->inserts[$insertStr][$x]);
                    }
                    $str .= $template;
                }
                $output = str_replace($hook->getHookString(), $str, $output);
            }
        }
        //trim trailing newline that gets added in...
        return substr($output, 0, -1);
    }

    public function getHooks() {
        return $this->hooks;
    }

    //Returns an array of all valid, fully qualified, insert strings
    public function getInsertStrings() {
        $inserts = [];
        foreach($this->hooks as $hook) {
            $inserts = array_merge($inserts, $hook->getInsertStrings());
        }
        return $inserts;
    }

    public function getInsertRegex() {
        return $this->insertRegex;
    }

    //Returns true if $insert matches any hook, otherwise false
    public function validInsert($insert) {
        $valid = preg_match($this->getInsertRegex(), $insert);
        if($valid === 1)
            return true;
        if($valid === 0)
            return false;
    }

    public function insert($hook, $content) {
        if(is_array($content)) {
            foreach($content as $k => $v) {
                $this->insert($hook.Hook::TAG_SEPARATOR.$k, $v);
            }
            return;
        }
        if($this->validInsert($hook)) {
            return $this->inserts[$hook][] = $content;
        }
        if(self::INSERT_STRICT)
            throw new TemplateNoSuchHookException("Invalid insert string: $hook");
    }

    public function insertFile($hook, $file) {
        $this->insert($hook, file_get_contents(self::CONTENT_DIR.$file));
    }

    public function replace($hook, $content) {
        $this->inserts[$hook] = [];
        $this->insert($hook, $content);
    }

    public static function readTemplate($file) {
        return file_get_contents(self::TEMPLATE_DIR.$file);
    }

    public static function extractBasicHooks($template) {
        preg_match_all(Hook::getBasicRegex(), $template, $hooks);
        return array_unique($hooks[1]);
    }

    public static function extractComplexHooks($template) {
        preg_match_all(Hook::getComplexRegex(), $template, $hooks);
        return array_unique($hooks[1]);
    }

    public static function extractHookStrings($template) {
        $hooks = self::extractBasicHooks($template);
        foreach(self::extractComplexHooks($template) as $hook) {
            $hook = explode(Hook::TAG_SEPARATOR, $hook);
            foreach(self::extractHookStrings(self::readTemplate($hook[1])) as $subHook) {
                $hooks[] = $hook[0].Hook::TAG_SEPARATOR.$subHook;
            }
        }
        return $hooks;
    }

    //not sure about this one...
    public static function extractHookArray($template) {
        $hooks = self::extractBasicHooks($template);
        foreach(self::extractComplexHooks($template) as $hook) {
            $hook = explode(Hook::TAG_SEPARATOR, $hook);
            foreach(self::extractHookArray(self::readTemplate($hook[1])) as $subHook) {
                $hooks[$hook[0]][] = $subHook;
            }
        }
        return $hooks;
    }

    public static function extractHooks($template, $mode = self::FROM_STRING) {
        $hooks = [];
        if($mode == self::FROM_FILE)
            $template = self::readTemplate($template);
        foreach(self::extractBasicHooks($template) as $hook) {
            $hooks[] = new Hook($hook);
        }
        foreach(self::extractComplexHooks($template) as $hook) {
            $h = new Hook($hook);
            foreach(self::extractHooks($h->getTemplate(), self::FROM_FILE) as $subHook) {
                $h->addChild($subHook);
            }
            $hooks[] = $h;
        }
        return $hooks;
    }

    public static function generateInsertRegex($hooks, $mode = 0) {
        $hookRegex = [];
        if($mode == 1) //1 = hooks is a template file
            $hooks = self::extractHooks($hooks);
        foreach($hooks as $hook) {
            $hookRegex[] = $hook->getInsertRegex(1);
        }
        return '/^(?:'.implode('|', $hookRegex).')$/U';
    }
}

//CLASS SPECIFIC EXCEPTIONS FOLLOW
interface ITemplateException {
}
interface ITemplateInstanceException extends ITemplateException {
}

class TemplateNoSuchHookException extends DomainException implements ITemplateInstanceException {
}

?>
